import { useNavigate, useLocation } from "react-router-dom";
import logo from "@/assets/logo.png";
import icons from "./iconList";
import React, { useState, useEffect, useCallback } from "react";
import { Menu } from "antd";
import type { MenuProps } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { setMenu } from "@/store/login/authSlice";
import { getMenuApi } from "@/api/users";
import "./index.scss";
interface MenuItemFromData {
  key: string;
  label: string;
  icon: string;
  children?: MenuItemFromData[];
}

// 添加折叠状态的类型定义
interface NavLeftProps {
  collapsed?: boolean;
}

const NavLeft: React.FC<NavLeftProps> = ({ collapsed = false }) => {
  const { menuList } = useSelector((state: any) => state.auth);
  const navigate = useNavigate();
  const location = useLocation();
  const [menuData, setMenuData] = useState<MenuProps["items"]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const dispatch = useDispatch();
  
  useEffect(() => {
    const fetchAndSetMenu = async () => {
      try {
        const { data } = await getMenuApi();
        dispatch(setMenu(data));
      } catch (error: any) {
        console.error("获取菜单失败:", error);
      }
    };
    fetchAndSetMenu();
  }, [dispatch]);

  //将返回的菜单数据转换成我们需要的格式
  const mapMenuItems = useCallback(function (items: MenuItemFromData[]): MenuProps['items'] {
    return items.map((item: MenuItemFromData) => ({
      key: item.key,
      label: item.label,
      icon: icons[item.icon as keyof typeof icons],
      children: item.children ? mapMenuItems(item.children) : null //递归操作
    }))
  }, []);

  useEffect(() => {
    if (menuList.length > 0) {
      const configMenu = async function () {
        const mappedMenuItems: MenuProps['items'] = mapMenuItems(menuList);
        setMenuData(mappedMenuItems);
      };
      configMenu();
    }
  }, [mapMenuItems, menuList]);

  // 查找当前路径对应的父级菜单项，用于展开对应的菜单
  useEffect(() => {
    if (collapsed || !menuData || menuData.length === 0) return;
    
    const findParentKeys = (items: any[], key: string, parentKeys: string[] = []): string[] | null => {
      for (const item of items) {
        if (item.key === key) {
          return [...parentKeys];
        }
        if (item.children) {
          const found = findParentKeys(item.children, key, [...parentKeys, item.key]);
          if (found) {
            return found;
          }
        }
      }
      return null;
    };

    const parentKeys = findParentKeys(menuData, location.pathname);
    if (parentKeys) {
      setOpenKeys(parentKeys);
    }
  }, [menuData, location.pathname, collapsed]);

  const handleOpenChange = (keys: string[]) => {
    setOpenKeys(keys);
  };

  function handleClick({ key }: { key: string }) {
    navigate(key);
  }

  return (
    <div className="navleft">
      <div className="logo">
        <img src={logo} alt="" width={18} />
        {!collapsed && <h1>朋远智慧园区</h1>}
      </div>
      <Menu
        defaultSelectedKeys={["/dashboard"]}
        mode="inline"
        theme="dark"
        items={menuData}
        onClick={handleClick}
        selectedKeys={[location.pathname]}
        openKeys={openKeys}
        onOpenChange={handleOpenChange}
      />
    </div>
  );
};

export default NavLeft;